﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.PurchaseCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.PurchaseCommandHandler
{
    /// <summary>
    /// 采购/委外显示命令处理
    /// </summary>
    public class PurchaseQueryCommandHandler : IRequestHandler<PurchaseQueryCommand, APIPaing<List<Purchase>>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 仓储-采购委外订单
        /// </summary>
        private readonly IBaseRepository<Purchase> purchaseRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="purchaseRepository"></param>
        public PurchaseQueryCommandHandler(IMapper mapper, IBaseRepository<Purchase> purchaseRepository)
        {
            this.mapper = mapper;
            this.purchaseRepository = purchaseRepository;
        }

        public async Task<APIPaing<List<Purchase>>> Handle(PurchaseQueryCommand request, CancellationToken cancellationToken)
        {
            APIPaing<List<Purchase>> result = new APIPaing<List<Purchase>>();
            var list = purchaseRepository.GetAll().Result.Where(o => o.IsDelete == 0);
            if (!string.IsNullOrEmpty(request.OrderCode))
            {

                list = list.Where(o => o.OrderCode == request.OrderCode);
            }
            if (!string.IsNullOrEmpty(request.OrderName))
            {
                list = list.Where(o => o.OrderName.Contains(request.OrderName));
            }
            if (!string.IsNullOrEmpty(request.Supplier))
            {

                list = list.Where(o => o.Supplier == request.Supplier);
            }
            if (request.Supplier != null)
            {

                list = list.Where(o => o.Supplier == request.Supplier);
            }
            if (request.Project != null)
            {

                list = list.Where(o => o.Project == request.Project);
            }
            if (request.ApprovalStatus!=null)
            {

                list = list.Where(o => o.ApprovalStatus == request.ApprovalStatus);
            }
            result.TotalCount = list.Count();
            result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
            list = list.OrderByDescending(o => o.Purchaseid).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            var data = mapper.Map<List<Purchase>>(list);
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = data;
            return await Task.FromResult(result);
        }
    }
}
